Given a positive integer num, write a function which returns True if num is a perfect square else False.
Follow up: Do not use any built-in library function such as sqrt.
判斷給定值是否為完全平方數
Input: num = 16
Output: true
Input: num = 14
Output: false
宣告最小數min = 1
,最大數max = Math.floor(num / 2)
,
使用二分法縮小範圍,取得中間值mid = (min + max) / 2
,
若mid
的平方小於參數,將min
設為mid
,
若mid
的平方大於參數,將max
設為mid
。
var isPerfectSquare = function (num) {
if (num < 1) return false;
if (num === 1) return true;
let min = 1;
let max = Math.floor(num / 2);
while (min <= max) {
let mid = (min + max) / 2;
if (mid * mid == num) {
return true;
} else if (mid * mid < num) min = Math.floor(mid + 1);
else {
max = Math.ceil(mid - 1);
}
}
return false
};